/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.economy.web.action.honorary;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import ar.uba.fi.posgrado.academy.model.Course;
import ar.uba.fi.posgrado.academy.model.Teacher;
import ar.uba.fi.posgrado.academy.service.CourseService;
import ar.uba.fi.posgrado.academy.service.TeacherService;
import ar.uba.fi.posgrado.common.exception.MissingArgumentException;
import ar.uba.fi.posgrado.common.util.CommonUtils;
import ar.uba.fi.posgrado.economy.model.Honorary;
import ar.uba.fi.posgrado.economy.service.HonoraryService;
import ar.uba.fi.posgrado.economy.web.form.honorary.HonoraryForm;

/**
 * Action que crea uno o mas {@link Honorary honorarios}.<br>
 * 
 * @author nicolas.gonzalez
 * @see Action
 */
public class CreateHonoraryAction extends Action {

    /** Logger */
    private static Logger logger = Logger.getLogger(CreateHonoraryAction.class);
    
    private HonoraryService honoraryService;
    private CourseService courseService;
    private TeacherService teacherService;
    
    /** IoC */
    public void setHonoraryService(HonoraryService honoraryService) {
        this.honoraryService = honoraryService;
    }
    /** IoC */
    public void setCourseService(CourseService courseService) {
        this.courseService = courseService;
    }
    /** IoC */
    public void setTeacherService(TeacherService teacherService) {
        this.teacherService = teacherService;
    }
    

    /**
     * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @SuppressWarnings("unchecked")
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("Por crear un(unos) honorario(s) ...");
        }
        HonoraryForm form = (HonoraryForm)actionForm;
        Teacher teacher = this.teacherService.getById(form.getTeacherId());
        Course course = this.courseService.getById(new Long(form.getCourseSelected()));
        Date validityFrom = CommonUtils.toDateFromStringStandard(form.getValidityFrom());
        Double value = form.getValue();
        String reason = form.getReason();
        
        int amount = form.getAmountToCreate();
        if (amount <= 0) {
            amount = 1; // Si ingresa un numero negativo o cero entonces se crea una sola
        }
        
        if (logger.isDebugEnabled()) {
            logger.debug(   "Informacion del honorario nuevo obtenido. Invocando al servicio de creacion " +  
                            " de honorario(s) " + amount + " vez(ces) ...");
        }
        for (int j = 0; j < amount; j++) {
            Honorary honorary = new Honorary();
            Date newValidityFrom = CommonUtils.addMonths(validityFrom, j);
            honorary.setValidityFrom(newValidityFrom);

            honorary.setTeacher(teacher);
            honorary.setCourse(course);
            honorary.setValue(value);
            honorary.setReason(reason);

            try {
                this.honoraryService.create(honorary);
            }
            catch (MissingArgumentException e) {
                logger.warn("Intentando crear un honorario sin los campos obligatorios...");

                form.setClear(false); // Evita q se limpie el form
                
                ActionMessages errors = new ActionMessages();
                errors.add("honorary.missingArguments", new ActionMessage(e.getMessage(), false));
                saveErrors(request, errors);
                
                return mapping.getInputForward();
            }
        }
        
        logger.info("Honorario(s) creado(s) con exito");
        return mapping.findForward("success");
    }
    
}
